const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

// 引入Word转PDF的库
const AdmZip = require('adm-zip')
const { WordExtractor } = require('word-extractor')
const pdf = require('html-pdf')
const fs = require('fs')

exports.main = async (event, context) => {
    try {
        // 检查必要参数
        if (!event || (!event.fileID && !event.fileContent)) {
            return { code: 1, message: '缺少必要参数: fileID 或 fileContent' }
        }

        // 获取文件内容
        let fileBuffer
        if (event.fileID) {
            // 从云存储下载文件
            const res = await cloud.downloadFile({
                fileID: event.fileID
            })
            if (!res || !res.fileContent) {
                return { code: 2, message: '文件下载失败' }
            }
            fileBuffer = fs.readFileSync(res.fileContent)
        } else if (event.fileContent) {
            // 直接使用base64编码的文件内容
            try {
                fileBuffer = Buffer.from(event.fileContent, 'base64')
            } catch (e) {
                return { code: 3, message: '文件内容解码失败' }
            }
        }

        // 检查文件是否有效
        if (!fileBuffer || fileBuffer.length === 0) {
            return { code: 4, message: '无效的文件内容' }
        }

        // 转换Word为PDF
        const extractor = new WordExtractor()
        let extracted
        try {
            extracted = await extractor.extract(fileBuffer)
        } catch (e) {
            return { code: 5, message: 'Word文件解析失败: ' + e.message }
        }

        const html = extracted.getBody()
        const pdfOptions = {
            format: 'A4',
            border: '10mm'
        }

        const pdfBuffer = await new Promise((resolve, reject) => {
            pdf.create(html, pdfOptions).toBuffer((err, buffer) => {
                if (err) return reject(err)
                resolve(buffer)
            })
        })

        // 上传PDF到云存储
        const uploadRes = await cloud.uploadFile({
            cloudPath: `converted/${Date.now()}.pdf`,
            fileContent: pdfBuffer
        })

        return {
            code: 0,
            message: '转换成功',
            data: {
                fileUrl: uploadRes.fileID
            }
        }
    } catch (err) {
        console.error('转换失败:', err)
        return {
            code: 2,
            message: `转换失败: ${err.message}`
        }
    }
}